<template>
	<view class="container-2">
		<!-- 顶部筛选区域 - 固定 -->
		<view class="filter-section fixed-filter">
			<u-row gutter="16" justify="space-between">
				<u-col span="6">
					<view class="filter-item" @click="showDatePicker = true">
						<text class="filter-label">所有日期</text>
						<view class="filter-value-wrap">
							<text class="filter-value">{{ selectedDate || '请选择日期' }}</text>
							<u-icon name="arrow-down" size="14" color="#999"></u-icon>
						</view>
					</view>
				</u-col>

				<u-col span="6">
					<view class="filter-item" @click="showStatusPicker = true">
						<text class="filter-label">汇报状态</text>
						<view class="filter-value-wrap">
							<text class="filter-value">{{ selectedStatus || '请选择状态' }}</text>
							<u-icon name="arrow-down" size="14" color="#999"></u-icon>
						</view>
					</view>
				</u-col>
			</u-row>
		</view>

		<!-- 内容区域：改为scroll-view，添加滚动监听 -->
		<scroll-view class="content-with-filter" scroll-y="true" @scrolltolower="handleScrollToLower"
			:lower-threshold="120" scroll-with-animation="true" ref="reportScrollView">
			<!-- 汇报列表 -->
			<view class="report-list">
				<view class="report-item" v-for="(item, index) in reportData" :key="index"
					@click="viewReportDetail(item)">
					<view class="item-left">
						<view class="user-info">
							<text class="user-name">{{ item.textPerformanceName }}</text>
							<u-tag :text="getStatusText(item.status)" :type="getStatusType(item.status)" size="mini"
								class="status-tag"></u-tag>
						</view>
						<text class="report-content">{{ item.performanceContent }} / {{item.unit}}</text>
					</view>
					<view class="item-right">
						<u-icon name="arrow-right" size="16" color="#ccc"></u-icon>
					</view>
				</view>

				<!-- 加载状态提示（触底加载时） -->
				<u-loadmore :status="loadStatus" :loading-text="loadText" margin="40rpx 0"
					@click="retryLoad"></u-loadmore>
			</view>

			<!-- 加载中提示（首次加载/筛选时） -->
			<u-loading-page v-if="isFirstLoading" class="first-loading"></u-loading-page>

			<!-- 空状态（无数据且非加载中） -->
			<u-empty v-if="!isFirstLoading && reportData.length === 0 && loadStatus !== 'loading'" mode="list"
				class="empty-state"></u-empty>
		</scroll-view>

		<!-- 日期选择弹窗 -->
		<u-datetime-picker :show="showDatePicker" v-model="dateValue" mode="date" :minDate="minDate" :maxDate="maxDate"
			:formatter="formatter" @confirm="onDateConfirm" @cancel="showDatePicker = false" title="选择日期"
			confirmColor="#2585f5"></u-datetime-picker>

		<!-- 状态选择弹窗 -->
		<u-picker :show="showStatusPicker" :columns="[statusOptions]" keyName="text" @confirm="onStatusConfirm"
			@cancel="showStatusPicker = false" title="选择状态" confirmColor="#2585f5"></u-picker>
	</view>
</template>

<script>
	import {
		selectPerformanceLog
	} from '@/common/api/renwu.js'
	export default {
		props: ['type'],
		data() {
			const now = new Date();
			const year = now.getFullYear();
			const month = now.getMonth();
			const day = now.getDate();

			return {
				// 筛选相关
				showDatePicker: false,
				showStatusPicker: false,
				selectedDate: '',
				selectedStatus: '',
				dateValue: Number(new Date()),
				minDate: Number(new Date(year - 1, 0, 1)),
				maxDate: Number(new Date(year + 1, 11, 31)),

				// 状态选项
				statusOptions: [{
						text: '全部状态',
						value: ''
					},
					{
						text: '完成',
						value: '0'
					},
					{
						text: '待审批',
						value: '1'
					},
					{
						text: '已驳回',
						value: '2'
					}
				],

				// 列表与分页
				reportData: [],
				pageNum: 1, // 修复初始页码：从1开始（原代码为2，导致首次加载跳过第一页）
				pageSize: 10,
				total: 0,

				// 加载状态
				isFirstLoading: true,
				isLoading: false,
				loadStatus: 'loadmore',
				loadText: '上拉加载更多'
			}
		},
		created() {
			this.fetchReportData();
			console.log(this.type)
		},
		methods: {
			// 获取状态标签类型
			getStatusType(status) {
				const typeMap = {
					'0': 'primary',
					'1': 'warning',
					'2': 'success',
					'3': 'error'
				}
				return typeMap[status] || 'info'
			},

			// 获取状态文本
			getStatusText(status) {
				const typeMap = {
					'0': '任务完成',
					'1': '待审批',
					'2': '驳回',
				}
				return typeMap[status] || ' '
			},

			// 日期格式化
			formatter(type, value) {
				if (type === 'year') return `${value}年`;
				if (type === 'month') return `${value}月`;
				if (type === 'day') return `${value}日`;
				return value;
			},

			// 日期筛选确认
			onDateConfirm(e) {				
				this.selectedDate = this.$formatTime(e.value,'YYYY-MM-DD')
				this.showDatePicker = false;
				// 重置分页并重新加载
				this.resetPagination();
				this.fetchReportData().then(() => {
					this.scrollToTop(); // 数据加载后滚动到顶部
				});
			},

			// 状态筛选确认
			onStatusConfirm(e) {
				console.log(e,'----')
				const selected = e.value[0];
				this.selectedStatus = selected.text;
				this.selectedStatusValue = selected.value;
				this.showStatusPicker = false;
				// 重置分页并重新加载
				this.resetPagination();
				this.fetchReportData().then(() => {
					this.scrollToTop(); // 数据加载后滚动到顶部
				});
			},
			// 3. 核心方法：让scroll-view滚动到顶部
			scrollToTop() {
				// 通过ref获取scroll-view实例，调用scrollTo方法
				this.$refs.reportScrollView.scrollTo({
					top: 0, // 滚动到顶部（距离顶部0px）
					duration: 300 // 滚动动画时长（毫秒），可选
				});
			},
			// 重置分页参数
			resetPagination() {
				this.pageNum = 1;
				this.reportData = [];
				this.total = 0;
				this.loadStatus = 'loadmore';
				this.isFirstLoading = true;
			},

			// 核心：请求数据（修复Promise链式调用问题）
			async fetchReportData() {
				// 防止重复请求
				if (this.isLoading) return;

				// 标记加载中
				this.isLoading = true;
				this.loadStatus = 'loading';
				this.loadText = '加载中...';

				try {
					// 构造请求参数
					const params = {
						pageNum: this.pageNum,
						pageSize: this.pageSize,
						createTime: this.selectedDate || '',
						status: this.selectedStatusValue || '',
						performanceType: 3, // （0：业绩任务 1：任务审计 2:任务汇报 3:开门红业绩任务）
					};
					if (this.type == 1) { // 任务管理-看汇报
						params.performanceType = 2
					}

					// 修复：使用async/await正确处理接口返回（原代码then嵌套导致状态更新异常）
					const res = await selectPerformanceLog(params);
					// 假设接口返回格式：{ data: { total: 总条数, records: 列表数据 } }
					const {
						total,
						records
					} = res.data;
					this.isLoading = false;
					this.total = total;
					this.reportData = [...this.reportData, ...records];

					// 判断是否还有更多数据
					if (this.reportData.length >= this.total) {
						this.loadStatus = 'noMore';
						this.loadText = '已加载全部数据';
					} else {
						this.loadStatus = 'loadmore';
						this.loadText = '上拉加载更多';
						this.pageNum++; // 页码自增
					}

				} catch (error) {
					// 错误处理
					this.loadStatus = 'error';
					this.loadText = '加载失败，点击重试';
					console.error('获取数据失败：', error);
				} finally {
					// 无论成功失败，都结束加载状态
					this.isLoading = false;
					this.isFirstLoading = false;
				}
			},

			// scroll-view触底事件：触发加载更多
			handleScrollToLower() {
				console.log('ggggggggggg', this.isLoading, this.loadStatus, this.reportData.length)
				// 满足条件才加载：非加载中、有更多数据、已有数据（非空）
				if (!this.isLoading && this.loadStatus === 'loadmore' && this.reportData.length > 0) {
					this.fetchReportData();
				}
			},

			// 加载失败重试
			retryLoad() {
				if (this.loadStatus === 'error') {
					this.fetchReportData();
				}
			},

			// 查看详情
			viewReportDetail(item) {
				if (this.type == 1) {
					uni.navigateTo({
						url: `/homeNav/rwgl/yjhb/rwhb_detail?id=${item.performanceId}&type=${this.type}`
					});
				} else {
					uni.navigateTo({
						url: `/homeNav/rwgl/yjhb/yjhb_detail?id=${item.performanceId}&type=${this.type}`
					});

				}
			}
		},
		// 移除重复的onReachBottom（改用scroll-view的@scrolltolower）
	}
</script>

<style scoped lang="scss">
	.container-2 {
		// background-color: #f5f5f5;
		// min-height: 100vh;
	}

	/* 固定筛选区域 */
	.fixed-filter {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 999;
		background: #fff;
		padding: 16rpx 30rpx;
		border-bottom: 1rpx solid #eee;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	/* 关键：scroll-view必须设置固定高度，否则无法滚动 */
	.content-with-filter {
		height: calc(100vh - 250rpx);
		/* 屏幕高度 - 筛选栏高度 = 滚动区域高度 */
		margin-top: 150rpx;
		/* 与筛选栏高度一致，避免被遮挡 */
		overflow: hidden;
		/* 隐藏溢出内容 */
	}

	/* 首次加载动画 */
	.first-loading {
		padding: 200rpx 0;
		text-align: center;
	}

	/* 筛选区域样式 */
	.filter-item {
		background-color: #f8f9fa;
		border-radius: 12rpx;
		padding: 0rpx 24rpx;
		height: 100rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		transition: all 0.3s;
	}

	.filter-item:active {
		background-color: #e9ecef;
	}

	.filter-label {
		font-size: 24rpx;
		color: #666;
		margin-bottom: 8rpx;
	}

	.filter-value-wrap {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.filter-value {
		font-size: 28rpx;
		color: #333;
		font-weight: 500;
	}

	/* 汇报列表样式 */
	.report-list {
		// padding: 20rpx;
	}

	.report-item {
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
		padding: 24rpx 0;
		background-color: #fff;
		border-radius: 16rpx;
		margin-bottom: 20rpx;
		transition: background-color 0.3s;
		border-bottom: 2rpx solid #f2f2f2;
	}

	.report-item:active {
		background-color: #f8f9fa;
	}

	.item-left {
		flex: 1;
		margin-right: 20rpx;
	}

	.user-info {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 16rpx;
	}

	.user-name {
		font-size: 30rpx;
		font-weight: 600;
		color: #333;
		margin-right: 16rpx;
	}

	.report-content {
		font-size: 26rpx;
		color: #666;
		line-height: 1.5;
		margin-bottom: 12rpx;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		overflow: hidden;
	}

	.item-right {
		display: flex;
		align-items: center;
		padding-top: 8rpx;
	}

	/* 空状态 */
	.empty-state {
		padding: 120rpx 0;
		text-align: center;
	}
</style>

<style lang="scss">
	/* 全局样式调整 */
	.u-col {
		padding-left: 8rpx !important;
		padding-right: 8rpx !important;
	}

	.status-tag {
		margin-left: 0 !important;
	}

	.u-datetime-picker .u-picker__view__column__item {
		font-size: 28rpx !important;
	}
</style>